import { DataTypes, Model } from 'sequelize';
import sequelize from '../utils/database';

export interface UserAttributes {
  id?: number;
  username: string;
  email: string;
  password: string;
  phone?: string;
  avatar?: string;
  nickname?: string;
  gender?: 0 | 1 | 2; // 0-未知，1-男，2-女
  birthday?: Date;
  status?: 0 | 1; // 0-禁用，1-正常
  levelId?: number;
  points?: number;
  balance?: number;
  lastLoginAt?: Date;
  createdAt?: Date;
  updatedAt?: Date;
}

export class User extends Model<UserAttributes> implements UserAttributes {
  public id!: number;
  public username!: string;
  public email!: string;
  public password!: string;
  public phone?: string;
  public avatar?: string;
  public nickname?: string;
  public gender?: 0 | 1 | 2;
  public birthday?: Date;
  public status!: 0 | 1;
  public levelId!: number;
  public points!: number;
  public balance!: number;
  public lastLoginAt?: Date;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  // 实例方法
  public toSafeJSON() {
    const { password, ...safeUser } = this.toJSON();
    return safeUser;
  }

  public getGenderText(): string {
    const genderMap = { 0: '未知', 1: '男', 2: '女' };
    return genderMap[this.gender || 0];
  }

  public getStatusText(): string {
    return this.status === 1 ? '正常' : '禁用';
  }
}

User.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    username: {
      type: DataTypes.STRING(50),
      allowNull: false,
      unique: true,
      comment: '用户名',
      validate: {
        len: [3, 50],
        notEmpty: true,
        isAlphanumeric: true,
      },
    },
    email: {
      type: DataTypes.STRING(100),
      allowNull: false,
      unique: true,
      comment: '邮箱',
      validate: {
        isEmail: true,
        notEmpty: true,
      },
    },
    password: {
      type: DataTypes.STRING(255),
      allowNull: false,
      comment: '密码（加密）',
      validate: {
        len: [6, 255],
        notEmpty: true,
      },
    },
    phone: {
      type: DataTypes.STRING(20),
      allowNull: true,
      unique: true,
      comment: '手机号',
      validate: {
        is: /^1[3-9]\d{9}$/,
      },
    },
    avatar: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: '头像URL',
    },
    nickname: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: '昵称',
      validate: {
        len: [1, 50],
      },
    },
    gender: {
      type: DataTypes.TINYINT,
      defaultValue: 0,
      comment: '性别：0-未知，1-男，2-女',
      validate: {
        isIn: [[0, 1, 2]],
      },
    },
    birthday: {
      type: DataTypes.DATEONLY,
      allowNull: true,
      comment: '生日',
    },
    status: {
      type: DataTypes.TINYINT,
      defaultValue: 1,
      comment: '状态：0-禁用，1-正常',
      validate: {
        isIn: [[0, 1]],
      },
    },
    levelId: {
      type: DataTypes.INTEGER,
      defaultValue: 1,
      comment: '会员等级ID',
      field: 'level_id',
    },
    points: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      comment: '积分',
      validate: {
        min: 0,
      },
    },
    balance: {
      type: DataTypes.DECIMAL(10, 2),
      defaultValue: 0,
      comment: '账户余额',
      validate: {
        min: 0,
      },
    },
    lastLoginAt: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: '最后登录时间',
      field: 'last_login_at',
    },
  },
  {
    sequelize,
    modelName: 'User',
    tableName: 'users',
    timestamps: true,
    underscored: true,
    indexes: [
      {
        fields: ['email'],
      },
      {
        fields: ['phone'],
      },
      {
        fields: ['status'],
      },
    ],
    hooks: {
      beforeCreate: (user: User) => {
        // 如果没有昵称，使用用户名作为昵称
        if (!user.nickname) {
          user.nickname = user.username;
        }
      },
    },
  }
);